<?php

namespace App\Exceptions;

use Error;
use Exception;
use Throwable;
use Illuminate\Validation\ValidationException;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;

class Handler extends ExceptionHandler
{
    /**
     * A list of exception types with their corresponding custom log levels.
     *
     * @var array<class-string<\Throwable>, \Psr\Log\LogLevel::*>
     */
    protected $levels = [
        //
    ];

    /**
     * A list of the exception types that are not reported.
     *
     * @var array<int, class-string<\Throwable>>
     */
    protected $dontReport = [];

    /**
     * A list of the inputs that are never flashed to the session on validation exceptions.
     *
     * @var array<int, string>
     */
    protected $dontFlash = [
        'current_password',
        'password',
        'password_confirmation',
    ];

    /**
     * Register the exception handling callbacks for the application.
     *
     * @return void
     */
    public function register()
    {
        // 注册自定义ApiHandler
        $this->renderable(function (FireFlyException $e) {
            return response()->json(['code' => $e->getCode(), 'message' => $e->getMessage(), 'result' => $e->getFile()]);
        });
        // 参数验证
        $this->renderable(function (ValidationException $e) {
            return response()->json(['code' => 400, 'message' => current(current($e->errors())), 'result' => $e->getFile()]);
        });
        // 404
        $this->renderable(function (ModelNotFoundException $e) {
            return response()->json(['code' => 404, 'message' => $e->getMessage(), 'result' => $e->getFile()]);
        });
        $this->renderable(function (NotFoundHttpException $e) {
            return response()->json(['code' => 404, 'message' => '没有找到对应的内容', 'result' => $e->getLine().'，'.$e->getMessage().'，'.$e->getFile()]);
        });
        // 其他500
        $this->renderable(function (Error $e) {
            return response()->json(['code' => 500, 'message' => '服务器忙', 'result' => $e->getLine().'，'.$e->getMessage().'，'.$e->getFile()]);
        });
        $this->renderable(function (Exception $e) {
            return response()->json(['code' => 500, 'message' => '服务器忙', 'result' => $e->getLine().'，'.$e->getMessage().'，'.$e->getFile()]);
        });
        $this->reportable(function (Throwable $e) {
            return response()->json(['code' => 500, 'message' => '服务器忙', 'result' => $e->getLine().'，'.$e->getMessage().'，'.$e->getFile()]);
        });
    }
}
